<script setup lang="ts">
import { BACKEND_BASE_URL, request } from "@/http/axios"
import ImageAnnotation from "@@/components/ImageAnnotation/index.vue"
import { ArrowLeft, ArrowRight } from "@element-plus/icons-vue"
import { uniqBy } from "lodash-es"
import { isObject } from "unocss"
import { nextTick, onMounted, ref } from "vue"
import { useRoute, useRouter } from "vue-router"
import tool from "./tool.vue"
import typePopver from "./typePopver.vue"
import { useTypePopver } from "./useTypePopver"

const { show, hide } = useTypePopver()
const route = useRoute()
const router = useRouter()
const isLoad = ref(false)
const currentIndex = ref(0)
const currentList = ref([])


const ImageAnnotationRef = ref()
const isEdit = ref(false)
const imgUrl = ref()
function handleToolClick(type: string) {
  console.log(type, "f")
  if (type === "highlight") {
    ImageAnnotationRef.value.handleDark()
    isEdit.value = true
    ImageAnnotationRef.value.setSelectable(true)
  } else if (type === "clearHighlight") {
    ImageAnnotationRef.value.handleClearDark()
    isEdit.value = false
    ImageAnnotationRef.value.setSelectable(false)
  } else if (type === "select") {
    isEdit.value = true
    ImageAnnotationRef.value.setSelectable(false)
  } else {
    isEdit.value = false
    ImageAnnotationRef.value.setSelectable(false)
  }
  hide()
}

function mouseUp() {
  const data = ImageAnnotationRef.value.getActiveObject()
  if (data) {
    show(ImageAnnotationRef.value)
  } else {
    hide()
  }
}
function mouseDown() {
  const data = ImageAnnotationRef.value.getActiveObject()
  if (!data) {
    hide()
  }
}
function getFormData(data = {}) {
  const formData = new FormData()
  for (const k in data) {
    const item = data[k as keyof typeof data]
    formData.append(k, item)
  }
  return formData
}
function getImageName(url: string) {
  const lastIndex = url.lastIndexOf("/")
  if (lastIndex === -1) {
    return url
  }
  return url.substring(lastIndex + 1)
}

async function handleSaveData() {
  const res = await saveData()
  if (res) {
    ElMessage({
      message: "保存成功",
      type: "success"
    })
  } else {
    ElMessage({
      message: "保存失败",
      type: "error"
    })
  }
}

async function saveData() {
  const data = ImageAnnotationRef.value.getRectData()
  console.log(data, "data")
  const filterData = uniqBy(data, "left").filter((item: any) => {
    return item.fill === "transparent"
  }).map((v: any) => {
    const json = {
      normCoords: v.normCoords,
      stroke: v.stroke
    }
    return json
  })
  const normCoords = filterData.map((item: any) => {
    return item.normCoords
  })
  const marked = {
    data: filterData,
    ai: normCoords
  }

  const dataParams = {
    dir_name: route.params.id,
    file: new File(imgUrl.value.split("/").slice(-1), "image.png"),
    marked: JSON.stringify(marked),
    file_name: getImageName(imgUrl.value)
  }
  const formData = getFormData(dataParams)
  console.log(formData, "formData")
  const res = await request<any>({
    url: "/upload/file",
    method: "post",
    data: formData
  })
  if (res && res.code === 200) {
    return true
  } else {
    return false
  }
}

const update = ()=>{
  console.log("update")
  saveData()
}

function back() {
  router.push("/dashboard")
}

const numberText = computed(() => {
  return `${currentIndex.value + 1}/${currentList.value.length}`
})

async function prev() {
  if (currentIndex.value > 0) {
    currentIndex.value--
    imgUrl.value = `${BACKEND_BASE_URL}/images/${currentList.value[currentIndex.value]}`
    await ImageAnnotationRef.value.initCanvas(imgUrl.value)
    setMarkData()
  }
  hide()
}
async function next() {
  if (currentIndex.value < currentList.value.length - 1) {
    currentIndex.value++
    imgUrl.value = `${BACKEND_BASE_URL}/images/${currentList.value[currentIndex.value]}`
    await ImageAnnotationRef.value.initCanvas(imgUrl.value)
    setMarkData()
  }

  hide()
}

function getMarkDetail() {
  const dataParams = {
    dir_name: route.params.id,
    file_name: getImageName(imgUrl.value)
  }
  const formData = getFormData(dataParams)
  const res = request<any>({
    url: `/marked`,
    method: "post",
    data: formData
  })
  return res
}

async function setMarkData() {
  const markDetail = await getMarkDetail()
  console.log(markDetail, "markDetail")
  if (isObject(markDetail.data)) {
    const arr = markDetail.data.ai
    const rectData = markDetail.data.data
    await nextTick()
    ImageAnnotationRef.value.drawRectanglesFromNormalized(arr, rectData)
  } else {
    const arr: any[] = []
    const rectData: any[] = []
    await nextTick()
    ImageAnnotationRef.value.drawRectanglesFromNormalized(arr, rectData)
  }
}

onMounted(async () => {
  console.log(route.params.id, "route")
  const res = await request<any>({
    url: `/file/list?dir_path=${route.params.id}/train`,
    method: "get"
  })
  console.log(res, "res")
  if (res.code === 200) {
    currentList.value = res.data
    currentIndex.value = 0
    imgUrl.value = `${BACKEND_BASE_URL}/images/${currentList.value[currentIndex.value]}`
  }
  isLoad.value = true
  await nextTick()
  ImageAnnotationRef.value.initCanvas(imgUrl.value)
  setMarkData()
})
</script>

<template>
  <div class="images-design">
    <div class="top">
      <div class="top-action">
        <el-button @click="back">
          返回
        </el-button>

        <el-button type="primary" @click="handleSaveData">
          保存
        </el-button>
      </div>
      <div class="top-image">
        <div class="nav">
          <el-icon @click="prev">
            <ArrowLeft />
          </el-icon>
          <div class="number">
            {{ numberText }}
          </div>
          <el-icon @click="next">
            <ArrowRight />
          </el-icon>
        </div>
      </div>
    </div>
    <div class="images-design-center">
      <div class="images-design-center-draw">
        <ImageAnnotation
          ref="ImageAnnotationRef"
          :img-url="imgUrl"
          :is-edit="isEdit"
          @mouse-up="mouseUp"
          @mouse-down="mouseDown"
          v-if="isLoad"
        />
        <typePopver @update="update"/>
      </div>
    </div>

    <tool @click="handleToolClick" />
  </div>
</template>

<style lang="scss" scoped>
.images-design {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
  .top {
    background-color: #fff;
    height: 56px;
    display: flex;
    align-items: center;
    padding: 0 10px;
  }
  .top-image {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
  }
  .nav {
    align-items: center;
    align-self: center;
    background-color: rgba(249, 250, 251, 1);
    border-radius: 9999px;
    border: 1px solid rgba(229, 231, 235, 1);
    display: flex;
    flex-direction: row;
    height: 40px;
    justify-content: space-between;
    padding: 10px;
    width: 11rem;
    cursor: pointer;
    .number {
      color: rgba(55, 65, 81, 1);
      font-size: 0.875rem;
      line-height: 1.25rem;
      user-select: none;
    }
  }
  .images-design-center {
    background-color: #f5f5f5;
    height: calc(100% - 56px);
    padding: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    .images-design-center-draw {
      width: 1600px;
      height: 100%;
      background-color: #fff;
      position: relative;
    }
  }
}
</style>
